from flask import Blueprint, request, jsonify
from collections import OrderedDict
from utils.utils import build_fail_response, confirm_params_type
from database.db_tools import SQLServerDatabase, connection_string
# 创建蓝图
ts_recheck_temp_res_page = Blueprint('ts_recheck_temp_res_page', __name__)



# 用户中途断网或者刷新页面，需要查询数据库保持原状态
@ts_recheck_temp_res_page.route('/pyapi/getTempByOrderNumber', methods=['GET'])
def getTempByOrderNumber():
    try:
        orderNumber = request.args.get('orderNumber')
        recheckEmployees = request.args.get('recheckEmployees')
        # 操作数据库
        with SQLServerDatabase(connection_string) as db:
            # 无需分页，查询全部
            res = db.execute_query_all("ts_recheck_temp_res", filters="orderNumber = ? and recheckEmployees = ?", params=[orderNumber, recheckEmployees])
            return jsonify(res)
    except Exception as e:
        return build_fail_response(message=str(e), params=confirm_params_type(request))

# 复检暂存表，当复检结束时会进行清空
@ts_recheck_temp_res_page.route('/pyapi/save_ts_recheck_temp_res', methods=['POST'])
def save_ts_recheck_temp_res():
    try:
        # 获取参数对象
        data = OrderedDict(sorted(request.json.items()))
        columns = []
        values = []
        # 封装key和value
        for key, value in data.items():
            columns.append(key)
            values.append(value)
        # 操作数据库
        with SQLServerDatabase(connection_string) as db:
            res = db.execute_insert("ts_recheck_temp_res", values=values, columns=columns)
            return jsonify(res)
    except Exception as e:
        return build_fail_response(message=str(e), params=confirm_params_type(request))


# 清空暂存表
@ts_recheck_temp_res_page.route('/pyapi/deleteTempResByOrderNumber', methods=['GET'])
def deleteTempResByOrderNumber():
    try:
        orderNumber = request.args.get('orderNumber')
        recheckEmployees = request.args.get('recheckEmployees')
        # 操作数据库
        with SQLServerDatabase(connection_string) as db:
            res = db.execute_delete("ts_recheck_temp_res", filters="orderNumber = ? and recheckEmployees = ?", params=[orderNumber,recheckEmployees])
            return jsonify(res)
    except Exception as e:
        return build_fail_response(message=str(e), params=confirm_params_type(request))